<template>
    <div class="cmt-container">
        <h3>发表评论</h3>
        <hr>
        <textarea placeholder="请输入你要说的" v-model="msg"></textarea>
        <mt-button type="primary" size="large" @click="postComment">发表评论</mt-button>
        <div class="cmt-list">
            <div class="cmt-item" v-for="(item,i) in comments" :key="item.index">
                <div class="cmt-title">第{{ i+1 }}楼<br />
                用户：{{ item.user_name }}&nbsp;&nbsp;{{ item.add_time | dataFormat}}</div>
                <div class="cmt-body">
                    {{ item.content==='' ? '此用户很懒，啥都没写': item.content}}
                </div>
            </div>

        </div>
        <mt-button class="more" plain type="danger" size="large" @click="getMore">加载更多</mt-button>
    </div>
</template>

<script>
import { Toast } from 'mint-ui';
export default {
    props:["id"],
    data() {
        return {
            pageIndex:1,
            comments:[],
            msg:''
        }
    },
    created(){
        this.getComments()
    },
    methods: {
        // 获取评论
        getComments(){
            this.$axios.get('api/getcomments/' +this.id+ '?pageindex=' +this.pageIndex)
            .then(res => {
                if(res.data.status === 0){
                    this.comments=this.comments.concat(res.data.message)
                    
                }else{
                    Toast('请求出错');
                }
            })
        },
        //加载更多
        getMore(){  
            this.pageIndex++;
            this.getComments()
        },
        // 发表评论
        postComment(){
            // 校验是否为空
            if(this.msg.trim().length===0){
                Toast('输入不能为空');
            }else{
                this.$axios.post('api/postcomment/' + this.id,{comment:this.msg.trim()})
            .then(res => {
                if(res.data.status === 0){
                    var cmt = {
                        user_name:'匿名用户',
                        add_time:Date.now(),
                        content:this.msg.trim()
                    }
                    this.comments.unshift(cmt)
                    this.msg=''
                }else{

                }
            })
            }
            
        }
    },
}
</script>

<style scoped>
.cmt-container h3{
    font-size: 16px;
}
.cmt-container textarea{
    font-size: 14px;
    height: 80px;
    margin: 0
}
.cmt-container .cmt-list .cmt-item{
    font-size: 13px;
    margin: 5px 0
}
.cmt-container .cmt-list .cmt-item .cmt-title{
    background-color: #ccc;
    line-height: 21px
}
.cmt-container .cmt-list .cmt-body{
    text-indent: 2rem;
    line-height: 21px;
}
.more{
    margin-bottom: 10px;
}
</style>